package com.jrzh.mvc.service.sys.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jrzh.bean.CheckResultBean;
import com.jrzh.common.cache.CacheManager;
import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.tools.CollectionTools;
import com.jrzh.common.tools.ValidateTools;
import com.jrzh.common.utils.AESUtil;
import com.jrzh.common.utils.HttpClientHelper;
import com.jrzh.common.utils.PasswordUtils;
import com.jrzh.common.utils.ReflectUtils;
import com.jrzh.framework.I18nHelper;
import com.jrzh.framework.base.convert.BaseConvertI;
import com.jrzh.framework.base.model.GeneralModel;
import com.jrzh.framework.base.repository.BaseRepository;
import com.jrzh.framework.base.service.impl.BaseServiceImpl;
import com.jrzh.framework.bean.ResultBean;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.mvc.constants.CacheConstants;
import com.jrzh.mvc.constants.SysConstant;
import com.jrzh.mvc.convert.sys.FileConvert;
import com.jrzh.mvc.convert.sys.UserConvert;
import com.jrzh.mvc.model.sys.FileModel;
import com.jrzh.mvc.model.sys.ManegeInfoModel;
import com.jrzh.mvc.model.sys.RoleModel;
import com.jrzh.mvc.model.sys.UserModel;
import com.jrzh.mvc.repository.sys.UserRepository;
import com.jrzh.mvc.search.sys.FileSearch;
import com.jrzh.mvc.search.sys.UserSearch;
import com.jrzh.mvc.service.sys.UserServiceI;
import com.jrzh.mvc.service.sys.manage.SysServiceManage;
import com.jrzh.mvc.view.sys.UserPasswordView;
import com.jrzh.mvc.view.sys.UserView;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<UserModel, UserSearch, UserView> implements UserServiceI{
	
	@Autowired
	UserRepository  userRepository;
	
	@Autowired
	UserConvert userConvert;
	
	@Autowired
	FileConvert fileConvert;
	
	@Autowired
	private SysServiceManage sysServiceManage;

	@Override
	public BaseRepository<UserModel, Serializable> getDao() {
		return userRepository;
	}
	
	@Override
	public BaseConvertI<UserModel, UserView> getConvert() {
		return userConvert;
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String findUserNamesByUserIds(String ids, String reg) throws ProjectException{
		String[] userIds = ids.split(reg);
		String[] userNames = new String[userIds.length];
		if(null != userIds && userIds.length > 0){
			for (int i = 0; i < userIds.length; i++) {
				UserModel user = this.findById(userIds[i]);
				if(null != user){
					userNames[i] = user.getName();
				}
			}
		}
		return StringUtils.join(userNames, reg);
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String[] findUserIdsByRoleId(String roleId) throws ProjectException{
		if(StringUtils.isBlank(roleId)) return new String[]{};
		RoleModel role = sysServiceManage.roleService.findById(roleId);
		List<UserModel> userList = role.getUsers();
		return CollectionTools.collect(userList, "id", new String[]{});
	}
	/**
	 * 后台新增系统用户
	 */
	@SuppressWarnings({ "all"})
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void addUser(UserView view, SessionUser user) throws ProjectException{
		String message = null;
		if(null == view.getRoleIds() || view.getRoleIds().length == 0){
			message = I18nHelper.getI18nByKey("message.assigning_roles", user);
		}else if(false == ValidateTools.isMobile(view.getTel())){
			message = I18nHelper.getI18nByKey("message.phone_error", user);
		}
		if(StringUtils.isNotBlank(message)){
			throw new ProjectException(message);
		}
		
		
		UserModel model = new UserConvert().addConvert(view);
		model.setStatus(SysConstant.USER_STATUS.NORMAL);
		
		model.setRoles(sysServiceManage.roleService.listInByField("id", view.getRoleIds()));
		this.add(model, user);
		
		if(StringUtils.isNotBlank(view.getPhotoFile())){
			FileModel file = fileConvert.convertByJsonStr(view.getPhotoFile());
			file.setFormId(model.getId());
			sysServiceManage.fileService.add(file, user);
		}
	}
	
	/**
	 * 编辑后台系统用户
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void editUser(String userId, UserView view, SessionUser user) throws ProjectException{
		/*if(null == view.getRoleIds() || view.getRoleIds().length == 0){
			message = I18nHelper.getI18nByKey("message.assigning_roles", user);
		}else if(false == ValidateTools.isMobile(view.getTel())){
			message = I18nHelper.getI18nByKey("message.phone_error", user);
		}
		if(StringUtils.isNotBlank(message)){
			throw new ProjectException(message);
		}*/
		
		
		UserModel model = sysServiceManage.userService.findById(userId);
		Integer status = model.getStatus();
		model = new UserConvert().editConvert(view, model);
		model.setStatus(status);
		
		//model.setRoles(sysServiceManage.roleService.listInByField("id", view.getRoleIds()));
		this.edit(model, user);
		//删除原有文件
		FileSearch fileSearch = new FileSearch();
		fileSearch.setEqKey("admin_user_photo");
		fileSearch.setEqualModel("sys_user");
		fileSearch.setEqualFormId(model.getId());
		List<FileModel> fileList = sysServiceManage.fileService.list(fileSearch);
		if(CollectionTools.isNotBlank(fileList)){
			for(FileModel file: fileList){
				sysServiceManage.fileService.deleteModel(file, user);
			}
		}
		if(StringUtils.isNotBlank(view.getPhotoFile())){
			FileModel file = fileConvert.convertByJsonStr(view.getPhotoFile());
			file.setFormId(model.getId());
			sysServiceManage.fileService.add(file, user);
			user.setPhoto(file.getUrl());
		}else{
			user.setPhoto(null);
		}
		//刷新登陆缓存
		user.setCode(model.getCode());
		user.setName(model.getName());
		CacheManager.clearOnly(user.getUuid());
		CacheManager.putCacheInfo(user.getUuid(), user, CacheConstants.LOGIN_TIME_OUT);
	}
	/**
	 * 启用/禁用
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResultBean changeStatus(String userId, SessionUser user) throws ProjectException{
		
		ResultBean result = new ResultBean();
		
		UserModel userModel = this.findById(userId);
		userModel.setIsDisable(!userModel.getIsDisable());
		this.edit(userModel, user);
		
		result.setStatus(ResultBean.SUCCESS);
		result.setMsg(I18nHelper.getI18nByKey("message.adjustment_success", user));
		return result;
	}
	/**
	 * 重置密码
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResultBean resetPassword(String userId, SessionUser user) throws ProjectException{
		
		ResultBean result = new ResultBean();
		
		UserModel userModel = this.findById(userId);
		userModel.setPassword(PasswordUtils.encryptPassword("888888", userModel.getSalt()));
		this.edit(userModel, user);
		result.setStatus(ResultBean.SUCCESS);
		result.setMsg(I18nHelper.getI18nByKey("message.reset_password", user));
		return result;
	}
	
	/**
	 * 修改密碼
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void changePassword(String userId, UserPasswordView view, SessionUser user) throws ProjectException{
		UserModel model = sysServiceManage.userService.findById(userId);
		
		if(StringUtils.isBlank(view.getOldPassword())) throw new ProjectException(I18nHelper.getI18nByKey("message.old_password_null", user));
		
		if(StringUtils.isBlank(view.getNewPassword())) throw new ProjectException(I18nHelper.getI18nByKey("message.new_password_null", user));
		
		if(view.getNewPassword().length()<6 || view.getNewPassword().length()>20) throw new ProjectException(I18nHelper.getI18nByKey("message.password_incorrect_format", user));
		
		if(!StringUtils.equals(view.getNewPassword(), view.getDuplicationPassword())) throw new ProjectException(I18nHelper.getI18nByKey("message.new_password_not_same", user));
		
		if(!StringUtils.equals(PasswordUtils.encryptPassword(view.getOldPassword(), model.getSalt()), model.getPassword())) throw new ProjectException(I18nHelper.getI18nByKey("message.password_error", user));
		
		if(StringUtils.equals(PasswordUtils.encryptPassword(view.getNewPassword(), model.getSalt()), model.getPassword())) throw new ProjectException(I18nHelper.getI18nByKey("message.old_password_same", user));
		
		model.setPassword(PasswordUtils.encryptPassword(view.getNewPassword(), model.getSalt()));
		
		this.edit(model, user);
	}
	
	@Override
	public void add(UserModel model, SessionUser user) throws ProjectException{
		String message = validate(model, user);
		if (StringUtils.isNotBlank(message)) throw new ProjectException(message);
		if(model instanceof GeneralModel){
			Date _time = new Date();
			ReflectUtils.setValue("createBy", model, user.format());
			ReflectUtils.setValue("createTime", model, _time);
			ReflectUtils.setValue("updateBy", model, user.format());
			ReflectUtils.setValue("updateTime", model, _time);
			if(null== ReflectUtils.getValue("isDisable", model)){
				ReflectUtils.setValue("isDisable", model, false);
			}
		}
		getDao().save(model);
		log.info("====開始校驗登錄用戶權限====");
		Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
		CheckResultBean info = new CheckResultBean();
		List<ManegeInfoModel> list = sysServiceManage.manegeInfoService.findAll();
		ManegeInfoModel sysInfo = new ManegeInfoModel();
		if(CollectionTools.isNotBlank(list)){
			sysInfo = list.get(0);
			JSONObject param1 = new JSONObject(true);
			List<Map> users = new ArrayList<Map>();
			Map<String, Object> param2 = new HashMap<String, Object>();
			param2.put("code", model.getCode() + "");
			param2.put("email", model.getEmail() + "");
			param2.put("tels", model.getTel() + "");
			param2.put("remark", model.getRemark() + "");
			users.add(param2);
			param1.put("sysCode", sysInfo.getSysCode());
			param1.put("loginCode", user.getCode());
			param1.put("UserList", users);
			param1.put("timestamp", Calendar.getInstance().getTimeInMillis() / 1000 + "");
			try {
				param1.put("sign", HttpClientHelper.getSign(SysConstant.MIYAO, param1));
			} catch (Exception e1) {
				e1.printStackTrace();
				throw new ProjectException(e1.getMessage());
			}
			String data = HttpClientHelper.postBody(SysConstant.SYSTEM_MANAGER + "checkUser/", AESUtil.encrypt(gson.toJson(param1), SysConstant.MIYAO), "UTF-8");
			// aes解密
			data = AESUtil.decrypt(data, SysConstant.MIYAO);
			data = gson.toJson(data).replace("\\", "");
			data = data.substring(1, data.length() - 1);
			//System.out.println("data====" + data);
			Map<String, String> dataMap = gson.fromJson(data, Map.class);
			info = new CheckResultBean();
			try {
				info = (CheckResultBean) ReflectUtils.mapToObject1(dataMap, CheckResultBean.class);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ProjectException(e.getMessage());
			}
			log.info("用户登陆到期时间为："+info.getEndTime());
			model.setEndTime(info.getEndTime());
			sysServiceManage.userService.edit(model, user);
			log.info("權限查詢響應==info==" + info.toString());
			Boolean flag = StringUtils.equals(info.getStatus(), "1") ? true : false;
			if (!flag){
				throw new ProjectException("权限校验失败，添加用户失败！");
			}
		}
			
	}
	
}
